package label

import (
	"context"
	"gitee.com/bobo-rs/idea-space-framework/framework/dao"
	"gitee.com/bobo-rs/idea-space-framework/framework/model"
	"gitee.com/bobo-rs/idea-space-framework/framework/service"
	"gitee.com/bobo-rs/idea-space-framework/maps"
	"gitee.com/bobo-rs/idea-space-framework/pkg/utils"
	"github.com/gogf/gf/v2/frame/g"
	"strings"
)

func init() {
	service.RegisterLabel(New())
}

func New() *sLabel {
	return &sLabel{}
}

var (
	// Columns 获取字段信息
	Columns = dao.Label.Columns()
)

// GetLabelList 获取标签列表
func (l *sLabel) GetLabelList(ctx context.Context, in model.LabelGetListInput) (out *model.LabelGetListOutput, err error) {
	var (
		where = make(map[string]interface{})
	)
	if len(strings.TrimSpace(in.Name)) > 0 {
		where[Columns.Name] = strings.TrimSpace(in.Name)
	}
	// 是否必须
	switch in.IsRequired {
	case 0, 1:
		where[Columns.IsRequired] = in.IsRequired
	}
	// 初始化
	out = &model.LabelGetListOutput{}
	err = l.GetLabelListAndTotal(ctx, model.LabelQueryListAndTotalInput{
		CommonPaginationItem: model.CommonPaginationItem{
			Page: in.Page,
			Size: in.Size,
		},
		Where: where,
	}, &out.Rows, &out.Total)
	if err != nil {
		return nil, err
	}
	// 数据为空
	if len(out.Rows) == 0 {
		return
	}

	// 标签值MAP
	valuesMap, err := l.ProcessLabelValueMapByLabelId(
		ctx, utils.NewArray(out.Rows).ArrayColumnsUniqueUnit(`id`)...,
	)

	// 处理数据
	for key, row := range out.Rows {
		if fmtRequired, ok := maps.LabelIsRequiredMap[row.IsRequired]; ok {
			row.FmtRequired = fmtRequired
		}
		// 标签值
		if value, ok := valuesMap[row.Id]; ok {
			row.Values = value
		}
		out.Rows[key] = row
	}
	return
}

// GetLabelInfo 获取标签详情信息
func (l *sLabel) GetLabelInfo(ctx context.Context, in model.LabelGetDetailInput) (out *model.LabelGetDetailOutput, err error) {
	out = &model.LabelGetDetailOutput{}
	// 获取标签详情
	err = l.GetLabelDetailById(ctx, in.Id, &out)
	return
}

// GetLabelShowList 获取标签展示列表
func (l *sLabel) GetLabelShowList(ctx context.Context) (out []model.LabelShowListItem, err error) {
	out = []model.LabelShowListItem{}
	// 获取数据列表
	err = l.ProcessLabelList(ctx, g.Map{}, &out)
	if err != nil {
		return nil, err
	}
	if len(out) == 0 {
		return
	}
	// 获取标签Map
	valuesMap, err := l.ProcessLabelValueMapByLabelId(
		ctx, utils.NewArray(out).ArrayColumnsUniqueUnit(`id`)...,
	)
	for key, item := range out {
		// 拆分标签值
		if value, ok := valuesMap[item.Id]; ok {
			item.Values = strings.Split(value, ",")
		}
		out[key] = item
	}
	return
}
